<template>
  <div>
    <form-content
      :rules="rules"
      :form-items="formItems"
      :beforeSubmit="beforeSubmit"
      :submitApi="submitApi"
      :formStateInit="detail"
      :preview="preview"
      :afterSubmit="afterSubmit"
    >
    </form-content>
  </div>
</template>

<script>
  import { ref, toRefs, toRef, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { message } from 'ant-design-vue';
  import { formItems, formItems2Rules } from './config';
  import { add, update, info } from '../api';

  export default {
    data() {
      return {
        formItems,
      };
    },
    setup(props, context) {
      const router = useRouter();
      const { query, name: routeName } = router.currentRoute.value;
      const rules = ref(formItems2Rules);
      const state = reactive({
        preview: routeName.includes('detail'),
        detail: {},
      });
      const afterSubmit = (res) => {
        res.code == 0 && message.success('提交成功');
        router.back();
      };
      const beforeSubmit = (data) => {
        data.pic = data.pic[0];
        return data;
      };

      const submitApi = (p) => {
        p.id = query.id ? Number(query.id) : query.id;
        return query.id ? update(p) : add(p);
      };

      if (query.id) {
        info({ id: Number(query.id) }).then((res) => {
          const { data } = res;
          data.pic = [data.pic];
          state.detail = data;
        });
      }

      return {
        ...toRefs(state),
        submitApi,
        beforeSubmit,
        afterSubmit,
        rules,
      };
    },
  };
</script>

<style scoped>
  .box-list {
    position: relative;
    border: 1px solid #eee;
    padding-top: 10px;
    margin-top: 10px;
  }
  .list-del-btn {
    position: absolute;
    right: 10px;
  }
</style>
